package com.example.shop.common.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(filterName = "AjaxSessionFilter",urlPatterns = "/*")
public class AjaxSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 允许跨域的url跟请求的一致,即不限制
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        // 允许跨域的请求方式：为"POST, GET, OPTIONS, DELETE"
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        //第一次的预检请求获知服务器是否允许该跨域请求：如果允许，才发起第二次真实的请求；如果不允许，则拦截第二次请求。
        //如果为0：表示每次异步请求都发起预检请求。
        resp.setHeader("Access-Control-Max-Age", "0");
        //允许请求头带有的字段
        resp.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers");
        //允许客户端携带验证信息,比如：cookie
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        //允许与前端的XDomainRequest对象建立连接
        resp.setHeader("XDomainRequestAllowed","1");
        chain.doFilter(req,resp);
    }

    @Override
    public void destroy() {
    }
}
